package handlers;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Date;

import common.classes.HeaderWorker;
import configurator.SettingOfServer;


public class PostHandler extends Handler {
	
	public PostHandler() {
		super();
	}
	
	public PostHandler(Handler next) {
		super(next);
	}
	
	@Override
	public void parseRequest(Socket socket, HeaderWorker header, String error) {
		if (error != null) {
			super.parseRequest(socket, header, error);
			return;
		}
		if (!header.getMethod().equals("POST")) {
			super.parseRequest(socket, header, error);
			return;
		}
		/*try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			int len = socket.getInputStream().available();
			char[] ch = new char[len];
			br.read(ch);
			StringBuilder sb = new StringBuilder();
			sb.append(ch);
			String request = sb.toString();
			String responseString = new String(configHandler(request));
			String head = "HTTP/1.1 200 OK\r\n" + "Server: Saimon's server/"
					+ (new Date()).toString() + "\r\n"
					+ "Content-Type: text/html\r\n" + "Content-Length: "
					+ responseString.length() + "\r\n"
					+ "Connection: keep-alive\r\n\r\n";
			socket.getOutputStream().write(head.getBytes());
			socket.getOutputStream().write(configHandler(request));
			socket.getOutputStream().flush();
		} catch (IOException e) {
			System.err.println(e);
		} finally {
			this.closeSocket(socket);
		}*/
		this.closeSocket(socket);
	}
	
	private byte[] HTMLLogin(boolean b) {
		try {
			FileInputStream fis = null;
			if (b)
				fis = new FileInputStream("data//saites//registerPage.html");
			else
				fis = new FileInputStream(
						"data//saites//registerErrorPage.html");
			int len = fis.available();
			byte[] bytes = new byte[len];
			fis.read(bytes);
			fis.close();
			return bytes;
		} catch (IOException e) {
			System.err.println(e);
		}
		return null;
	}

	private byte[] HTMLSettings() {
		try {
			FileInputStream fis = null;
			fis = new FileInputStream("data//saites//configServerPage.html");
			int len = fis.available();
			byte[] bytes = new byte[len];
			fis.read(bytes);
			fis.close();
			return bytes;
		} catch (IOException e) {
			System.err.println(e);
		}
		return null;
	}

	private byte[] configHandler(String request) {
		if (request.indexOf("GET /admin") == 0) {
			return HTMLLogin(true);
		}
		if (request.indexOf("page=registration") >= 0) {
			int l, p;
			if (((l = request.indexOf("txtLogin")) >= 0)
					&& ((p = request.indexOf("txtPassword")) >= 0)) {
				int logBegin = l + 9;
				int logEnd = request.indexOf("&", logBegin);
				int passBegin = p + 12;
				int passEnd = request.length() - 1;
				if ((request.substring(logBegin, logEnd).equals("admin"))
						&& (request.substring(passBegin, passEnd).trim()
								.equals("1719"))) {
					return HTMLSettings();
				} else {
					return HTMLLogin(false);
				}
			}
		}

		if (request.indexOf("page=configuration") >= 0) {
			rewriteConfigurator(request);
			return HTMLSettings();
		}
		return null;
	}

	private void rewriteConfigurator(String request) {
		String path = request.substring(request.indexOf("txtConfPath") + 12,
				request.indexOf(("&"), request.indexOf("txtConfPath")));
		if (!path.equals("")) {
			Server.getConf().setConfFile(new File(path));
			return;
		}

		SettingOfServer settings = new SettingOfServer();
		settings.setServerType(request.substring(request.indexOf("type") + 5,
				request.indexOf(("&"), request.indexOf("type"))));
		settings.setRootPath(request.substring(
				request.indexOf("txtServerPath") + 14,
				request.indexOf("&", request.indexOf("txtServerPath"))));
		settings.setPort(Integer.parseInt(request.substring(
				request.indexOf("txtPort") + 8,
				request.indexOf("&", request.indexOf("txtPort")))));
		settings.setLogPath(request.substring(
				request.indexOf("txtLogPath") + 11,
				request.indexOf("&", request.indexOf("txtLogPath"))));
		if (request.substring(request.indexOf("txtSessionSupport") + 18,
				request.indexOf("&", request.indexOf("txtSessionSupport")))
				.equals("on"))
			settings.setSessionSupport(true);
		else
			settings.setSessionSupport(false);
		settings.setTimeout(Integer.parseInt(request.substring(
				request.indexOf("txtTimeout") + 11,
				request.indexOf("&", request.indexOf("txtTimeout")))));
		int[] persents = new int[2];
		persents[0] = Integer.parseInt(request.substring(
				request.indexOf("txtX") + 5,
				request.indexOf(("&"), request.indexOf("txtX"))));
		persents[0] = Integer.parseInt(request.substring(
				request.indexOf("txtY") + 5,
				request.indexOf(("&"), request.indexOf("txtY"))));
		persents[2] = 100 - persents[1] - persents[0];
		settings.setPersents(persents);
		String saits = request
				.substring(
						request.indexOf("txtSubsidiariesServers") + 23,
						request.indexOf("&",
								request.indexOf("txtSubsidiariesServers")));
		for (int i = 0; !saits.split("\r\n", i).equals(""); i++)
			settings.setSubsidiariesServersByIndex(i, saits.split("\r\n", i)
					.toString());

		Server.getConf().setSettings(settings);
	}
	
}
